<template>
  <div class="grid" style="gap: 8px">
    <GlassCard>
      <el-form label-position="top" label-width="auto" class="inc-compact">
        <el-form-item label="计算模式">
          <SegPills v-model="state.mode" :options="modeOptions" />
        </el-form-item>
      </el-form>

      <el-form label-position="left" label-width="auto" class="inc-compact">
        <div style="display: grid; grid-template-columns: 1fr">
          <el-form-item label="初始值">
            <div class="row-input">
              <el-input-number
                v-model="state.start"
                :min="0"
                :disabled="state.mode === 'start' ? true : false"
                :style="{ width: '180px' }"
                controls-position="right" />
              <el-button
                circle
                text
                size="small"
                @click="copyToClipboard(state.start)">
                <el-icon><DocumentCopy /></el-icon>
              </el-button>
            </div>
          </el-form-item>
          <el-form-item label="结束值">
            <div class="row-input">
              <el-input-number
                v-model="state.end"
                :min="0"
                :disabled="state.mode === 'end' ? true : false"
                :style="{ width: '180px' }"
                controls-position="right" />
              <el-button
                circle
                text
                size="small"
                @click="copyToClipboard(state.end)">
                <el-icon><DocumentCopy /></el-icon>
              </el-button>
            </div>
          </el-form-item>
        </div>

        <el-form-item label="增长率（%）">
          <div class="row-input">
            <el-input-number
              v-model="state.ratePercent"
              :min="-100"
              :max="1000"
              :step="0.01"
              :precision="2"
              :disabled="state.mode === 'rate'"
              :style="{ width: '180px' }"
              controls-position="right" />
            <el-button
              circle
              text
              size="small"
              @click="copyToClipboard(state.ratePercent)">
              <el-icon><DocumentCopy /></el-icon>
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </GlassCard>
  </div>
</template>

<script setup lang="ts">
import { DocumentCopy } from "@element-plus/icons-vue"
import {
  ElButton,
  ElForm,
  ElFormItem,
  ElIcon,
  ElInputNumber,
  ElMessage,
  ElRadioButton,
  ElRadioGroup
} from "element-plus"
import { computed, onMounted, reactive, watch } from "vue"

// @ts-ignore - SFC default export by Vue plugin
import GlassCard from "./ui/GlassCard.vue"
// @ts-ignore - SFC default export by Vue plugin
import SegPills from "./ui/SegPills.vue"

type Mode = "rate" | "start" | "end"

const state = reactive({
  start: 1,
  end: 2,
  mode: "rate" as Mode,
  ratePercent: 10
})

const modeOptions = [
  { label: "计算增长率", value: "rate" },
  { label: "计算结束值", value: "end" },
  { label: "计算初始值", value: "start" }
]

// 移除单位/时长相关逻辑

const DECIMAL_PLACES = 8
const EPS = 1e-12
function roundTo(value: number, places = DECIMAL_PLACES): number {
  const factor = Math.pow(10, places)
  return Math.round((value + EPS) * factor) / factor
}
function isFiniteNumber(v: number): boolean {
  return typeof v === "number" && isFinite(v)
}
function validInputs(): boolean {
  return state.start > 0 && state.end >= 0
}

// 直接把结果回写到相应输入框
function recompute() {
  if (state.mode === "rate") {
    if (state.start > 0) {
      const r = roundTo(state.end / state.start - 1)
      state.ratePercent = roundTo(r * 100, 2)
    }
    return
  }
  const r = Number(state.ratePercent) / 100
  if (!isFiniteNumber(r)) return
  if (state.mode === "start") {
    state.start = roundTo(state.end / (1 + r))
  } else if (state.mode === "end") {
    state.end = roundTo(state.start * (1 + r))
  }
}

watch(
  () => [state.mode, state.start, state.end, state.ratePercent],
  () => recompute(),
  { immediate: true }
)

onMounted(() => {
  loadCache().then(() => recompute())
})

// ---- Local cache ----
const CACHE_KEY = "calc_increase_rate_state_v1"
function applyCachedData(data: any) {
  if (typeof data !== "object" || data === null) return
  if (data.start != null) state.start = Number(data.start)
  if (data.end != null) state.end = Number(data.end)
  if (data.ratePercent != null) state.ratePercent = Number(data.ratePercent)
  if (data.mode === "rate" || data.mode === "start" || data.mode === "end") {
    state.mode = data.mode as Mode
  }
}
function loadCache(): Promise<void> {
  return new Promise((resolve) => {
    try {
      const c: any = (globalThis as any).chrome
      if (c && c.storage && c.storage.local) {
        c.storage.local.get(CACHE_KEY, (res: any) => {
          const data = res ? (res as any)[CACHE_KEY] : undefined
          applyCachedData(data)
          resolve()
        })
      } else {
        const raw = localStorage.getItem(CACHE_KEY)
        if (raw) applyCachedData(JSON.parse(raw))
        resolve()
      }
    } catch {
      resolve()
    }
  })
}

async function copyToClipboard(value: number) {
  try {
    await navigator.clipboard.writeText(String(value))
    ElMessage.success("已复制")
  } catch (e) {
    ElMessage.error("复制失败")
  }
}
function saveCache() {
  try {
    const payload = {
      start: state.start,
      end: state.end,
      ratePercent: state.ratePercent,
      mode: state.mode
    }
    const c: any = (globalThis as any).chrome
    if (c && c.storage && c.storage.local) {
      c.storage.local.set({ [CACHE_KEY]: payload })
    } else {
      localStorage.setItem(CACHE_KEY, JSON.stringify(payload))
    }
  } catch {}
}
let saveTimer: any
function scheduleSave() {
  clearTimeout(saveTimer)
  saveTimer = setTimeout(saveCache, 200)
}

watch(
  () => [state.mode, state.start, state.end, state.ratePercent],
  () => scheduleSave(),
  { immediate: false }
)
</script>

<style scoped>
.inc-compact :deep(.el-form-item) {
  margin-bottom: 10px;
}
.row-input {
  display: flex;
  align-items: center;
  gap: 4px;
}
.row-input :deep(.el-input-number) {
  flex: none;
}
.row-input .el-button {
  flex: none;
}
</style>
